package com.pitaya.avatar.util;

import java.util.regex.Pattern;

public class StringMatcher {
	
	private static String CN_LETTER = "[\\u4e00-\\u9fa5]";
	private static String CN_WORD = "[\\u4e00-\\u9fa5]+";
	private static String EN_LETTER = "[a-zzA-Z]";
	private static String SEPERATOR = "!";
	private static String SPECIAL_PYLETTER = "aegnory";
	private static Pattern P_CN_LETTER;
	private static Pattern P_CN_WORD;
	private static Pattern P_EN_LETTER;
	
	static{
		P_CN_LETTER = Pattern.compile(CN_LETTER);
		P_EN_LETTER = Pattern.compile(EN_LETTER);
		P_CN_WORD = Pattern.compile(CN_WORD);
	}
	
	private boolean isSpecial(String l){
		return SPECIAL_PYLETTER.indexOf(l) > -1;
	}
	
	public boolean isCNWord(String key){
		return P_CN_WORD.matcher(key).matches();
	}
	
	public boolean checkKey(String key){
		return key.indexOf(SEPERATOR) == -1;
	}
	
	public boolean isMatch(String key, String objstr, String letterstr){
		if(this.isCNWord(key)){
			//todo dynamic match
			if(objstr.indexOf(key) > -1)
				return true;
			else
				return false;
		} else {
			int key_idx = 0;
			int letter_idx = 0;
			int key_length = key.length();
			int letterstr_length = letterstr.length();
			String [] words = letterstr.split(SEPERATOR);
			while(letter_idx < letterstr_length){
				String character = String.valueOf(key.charAt(key_idx));
				int idx;
				if(P_CN_LETTER.matcher(character).matches()){
					if((idx = objstr.indexOf(character)) > -1){
						String py = words[idx];
						idx = letterstr.indexOf(py, letter_idx);
						if(idx == -1){
							return false;
						} else {
							letter_idx = idx + py.length();
						}
						if(++key_idx == key_length)
							return true;
					} else {
						return false;
					}
				} else if(P_EN_LETTER.matcher(character).matches()){
					if((idx = letterstr.indexOf(character, letter_idx)) == -1)
						return false;
					if(idx == 0 || letterstr.charAt(idx-1) == SEPERATOR.charAt(0) || letter_idx == idx ){
						letter_idx = idx + 1;
						if(++key_idx == key_length)
							return true;
					} else if(this.isSpecial(character)){
						letter_idx = idx + 1;
					} else {
						return false;
					}
				} else {
					if((idx = letterstr.indexOf(character, letter_idx)) == -1){
						return false;
					} else {
						letter_idx = idx + 1;
						if(++key_idx == key_length)
							return true;
					}
				}
			}
			return false;	
		}
	}
	
}
